package com.bw.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSON;
import com.bw.entity.Assets;
import com.bw.entity.Dict;
import com.bw.mapper.AssetsMapper;
import com.bw.service.AssetsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AssetsServiceImpl implements AssetsService {


    @Autowired
    AssetsMapper assetsMapper;


    @Transactional
    //返回资产对象
    @Override
    public Assets add(Assets assets) {
        //非空验证
        Integer typeId = assets.getTypeId();

        if (typeId == null) {
            throw new RuntimeException("类别不能为空");
        }
        Integer sourceId = assets.getSourceId();
        // hutool  工具类  断言    确信某一个变量 不为  null  如果是null  我就抛出异常
        Assert.notNull(sourceId, "来源不能为空");
        // 校验字符串  是否为空
        Assert.notBlank(assets.getName(), "名称不为空");
        Assert.notBlank(assets.getNum(), "编号不为空");
        Assert.notBlank(assets.getPrice(), "价格不为空");

        // 资产编号唯一性校验
        Assets assetsFromDB = assetsMapper.selectByNum(assets.getNum());

        if (assetsFromDB != null){
            throw new RuntimeException("资产编号重复");
        }
        //购入价格校验，必须为数值类型

        boolean number = NumberUtil.isNumber(assets.getPrice());
        if (!number){
            throw new RuntimeException("购入价格必须为数值类型");
        }
        //控制打印方法参数
        System.out.println("打印方法的参数 " + JSON.toJSONString(assets));

        assetsMapper.add(assets);
        System.out.println("添加成功， 成功之后那条数据的主键id是:" + assets.getId());

        return assets;
    }

    @Override
    public Assets selectByNum(String num) {
        // 查询要修改的数据
        Assets assets = assetsMapper.selectByNum(num);
        // 查询两个下拉框
        List<Dict> typeList =  assetsMapper.selectType();
        List<Dict> sourceList =  assetsMapper.selectSource();

        assets.setTypeList(typeList);
        assets.setSourceList(sourceList);
        return assets;
    }
}
